﻿using System;
using System.Security.Principal;
using System.Web;
using System.Web.Profile;
using System.Web.Security;
using uForum.Configuration;

namespace uForum.Businesslogic.Services
{
	public class AuthorizationService
	{
		private readonly IPrincipal _currentPrincipal;
		private const string EveryoneGroup = "Authorized";

		public AuthorizationService()
		{
			_currentPrincipal = HttpContext.Current.User;
		}

		public bool IsLoggedOn
		{
			get
			{
				return _currentPrincipal.Identity.IsAuthenticated;
			}
		}

		public Rights GetRights(int forumId)
		{
			string posters = Library.Utills.GetPropertyRecursive(forumId, ContentProperties.ForumPosterGroupAlias);
			bool canPost = string.IsNullOrEmpty(posters) ? false : userIsInGroups(posters);
			string admins = Library.Utills.GetPropertyRecursive(forumId, ContentProperties.ForumAdminGroupAlias);
			bool canAdmin = string.IsNullOrEmpty(admins) ? false : userIsInGroups(admins);
			return new Rights(canPost, canAdmin);
		}

		private bool userIsInGroups(string groups)
		{
			foreach (var group in groups.Split(','))
			{
				if (_currentPrincipal.IsInRole(group.Trim())) return true;
				if (group.Trim().Equals(EveryoneGroup) && _currentPrincipal.Identity.IsAuthenticated) return true;
			}
			return false;
		}

		public string GetUserId()
		{
			var factory = new ConverterFactory();
			IMemberIdConverter converter = factory.GetProviderKeyConverter();
			return converter.ConvertToString(Membership.GetUser().ProviderUserKey);
		}

		public string GetUserName(string id)
		{
			var factory = new ConverterFactory();
			IMemberIdConverter converter = factory.GetProviderKeyConverter();
			object provId = converter.ConvertToProviderKey(id);
			MembershipUser user = Membership.GetUser(provId);
			return user != null ? user.UserName : "Unknown";
		}
	}
}